package cn.suzhang.jsharp.common.config.data;

import java.util.Map;

import javax.persistence.EntityManager;
import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

/**
 * sys数据源详细配置
 * 
 * @author zhangsu
 *
 */
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef = "sysEntityManagerFactory", // 实体管理引用
        transactionManagerRef = "sysTransactionManager", // 事务管理引用
        basePackages = { "cn.suzhang.jsharp.module.sys" }) // 设置用户数据源所应用到的包
public class SysDataSourceConfig {

    /**
     * Autowired 按类型装配,Resource 按名称装配
     */
    @Autowired
    @Qualifier("sysDataSource")
    private DataSource userDataSource;

    @Autowired
    private JpaProperties jpaProperties;

    private Map<String, String> getVendorProperties(DataSource dataSource) {
        return jpaProperties.getHibernateProperties(dataSource);
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean sysEntityManagerFactory(EntityManagerFactoryBuilder builder) {
        return builder.dataSource(userDataSource).properties(getVendorProperties(userDataSource))
                .packages(new String[] { "cn.suzhang.jsharp.module.sys" })// 设置实体类所在位置
                .persistenceUnit("sysPersistenceUnit").build();
    }

    @Bean
    public EntityManager sysEntityManager(EntityManagerFactoryBuilder builder) {
        return sysEntityManagerFactory(builder).getObject().createEntityManager();
    }

    @Bean
    public PlatformTransactionManager sysTransactionManager(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(sysEntityManagerFactory(builder).getObject());
    }
}
